package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.PageDO;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.FileAuditDO;
import com.bootdo.system.domain.ReportDo;
import com.bootdo.system.domain.UserFileDO;
import com.bootdo.system.service.FileAuditService;
import com.bootdo.system.service.UserFileService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件审批控制管理类
 */
@RequestMapping("/sys/fileAudit")
@Controller
public class FileAuditController extends BaseController {

    private String prefix = "system/log";

    @Autowired
    private FileAuditService fileAuditService;

    @Autowired
    private UserFileService userFileService;

    /**
     * 待审批
     * @return
     */
    @GetMapping("/fileAuditCheck")
    String fileAuditCheck(){
        return "system/fileAudit/checkFileAudit";
    }

    /**
     * 已审批
     * @return
     */
    @GetMapping()
    String fileAudit(){
        return "system/fileAudit/fileAudit";
    }

    @ResponseBody
    @GetMapping("/list")
    public PageUtils list(@RequestParam Map<String, Object> params){
        //查询列表数据
        params.put("userid",getUserId().toString());
        Query query = new Query(params);
        List<FileAuditDO> auditList = fileAuditService.list(query);
        int total = fileAuditService.count(query);
        PageUtils pageUtils = new PageUtils(auditList, total);
        return pageUtils;
    }

    /**
     * 审批页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/check/{id}")
    String check(@PathVariable("id") Integer id,Model model){
        FileAuditDO fileAuditDO = fileAuditService.get(id);
        model.addAttribute("fileAuditDO", fileAuditDO);
        return "system/fileAudit/check";
    }

    /**
     * 审批
     */
    @ResponseBody
    @Log("文件审批")
    @RequestMapping("/check")
    public R check(FileAuditDO fileAuditDO){
        fileAuditDO.setAuditid(Integer.parseInt(getUserId().toString()));
        fileAuditService.update(fileAuditDO);
        return R.ok();
    }

    /**
     * 审批页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/detail/{id}")
    String detail(@PathVariable("id") Integer id,Model model){
        FileAuditDO fileAuditDO = fileAuditService.get(id);
        model.addAttribute("fileAuditDO", fileAuditDO);
        return "system/fileAudit/detail";
    }

    /**
     * 自己待审批
     * @return
     */
    @GetMapping("/myFileAuditCheck")
    String myFileAuditCheck(){
        return "system/fileAudit/myCheckFileAudit";
    }

    /**
     * 自己已审批
     * @return
     */
    @GetMapping("/myFileAudit")
    String myFileAudit(){
        return "system/fileAudit/myFileAudit";
    }

    /**
     * 删除
     */
    @PostMapping( "/remove")
    @Log("删除审批记录")
    @ResponseBody
    public R remove( Integer id){
        if(fileAuditService.remove(id)>0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping( "/batchRemove")
    @Log("删除审批记录")
    @ResponseBody
    public R remove(@RequestParam("ids[]") Integer[] ids){
        fileAuditService.batchRemove(ids);
        return R.ok();
    }


    /**
     * 文件审批日志首页
     * @return
     */
    @GetMapping("/auditLogList")
    @RequiresPermissions("sys:fileAudit:auditLogList")
    String auditList(){
        return "system/log/auditLogList";
    }


    /**
     * 文件审批日志报表
     */
    @ResponseBody
    @GetMapping("/listLog")
    @RequiresPermissions("sys:fileAudit:auditLogList")
    public PageUtils listLog(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("sendid",userId);
        params.put("auditstate",0);
        //查询列表数据
        Query query = new Query(params);
        List<FileAuditDO> auditList = fileAuditService.listLog(query);
        int total = fileAuditService.listLogConut(query);
        PageUtils pageUtils = new PageUtils(auditList, total);
        return pageUtils;
    }

    /**
     * 文件发送记录导出
     */
    @ResponseBody
    @GetMapping("/listLogExcel")
    public ResponseEntity<byte[]> listLogExcel(String filename,String startDate,String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("filename",filename);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("sendid",userId);
            params.put("auditstate",0);
            List<FileAuditDO> auditList = fileAuditService.listLog(params);
            return ExcelFormatUtil.buildResponseEntity(export(auditList), "管理员审批记录表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 文件审批日志首页
     * @return
     */
    @GetMapping("/sendlistLog")
    @RequiresPermissions("sys:fileAudit:sendlistLog")
    String sendList(){
        return "system/log/sendLogList";
    }

    /**
     * 文件发送日志报表
     */
    @ResponseBody
    @GetMapping("/sendLog")
    @RequiresPermissions("sys:fileAudit:sendlistLog")
    public PageUtils sendLog(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("sendid",userId);
        //查询列表数据
        Query query = new Query(params);
        List<FileAuditDO> auditList = fileAuditService.listLog(query);
        int total = fileAuditService.listLogConut(query);
        PageUtils pageUtils = new PageUtils(auditList, total);
        return pageUtils;
    }


    /**
     * 文件发送记录导出
     */
    @ResponseBody
    @GetMapping("/sendLogExcel")
    public ResponseEntity<byte[]> sendLogExcel(String filename,String startDate,String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("filename",filename);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("sendid",userId);
            List<FileAuditDO> auditList = fileAuditService.listLog(params);
            return ExcelFormatUtil.buildResponseEntity(export(auditList), "文件发送记录表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream export(List<FileAuditDO> auditList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] { "发送用户", "接受用户", "审批人", "文件名", "类型","发送时间","发送备注","审批备注","审批结果"};

        // 字段名所在表格的宽度
        int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000,5000, 5000, 5000};

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

        if (auditList != null && auditList.size() > 0) {
            for (int i = 0; i < auditList.size(); i++) {
                FileAuditDO fileAuditDO = auditList.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getSendname()); // 发送用户
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getTargetname()); // 接受用户
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getAuditname()); // 审批人
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getFilename()); // 文件名
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getFiletype()); // 类型
                cell.setCellStyle(content);

                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                cell = row.createCell(j++);
                cell.setCellValue(sdf.format(fileAuditDO.getSendtime())); // 发送时间
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getSendcmt()); // 发送备注
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(fileAuditDO.getAuditcmt()); // 审批备注
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                if(fileAuditDO.getAuditstate().equals("0") ){
                    cell.setCellValue("待审批"); // 审批结果
                }else if(fileAuditDO.getAuditstate().equals("1")){
                    cell.setCellValue("审批通过");
                }else if(fileAuditDO.getAuditstate().equals("2")){
                    cell.setCellValue("审批不通过");
                }else{
                    cell.setCellValue("免审批");
                }
                cell.setCellStyle(content);
            }
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null){
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }




    /**
     * 首页折线图/柱状图/饼状图
     */
    @ResponseBody
    @PostMapping("/getCountAudit")
    public R getCountAudit(){
        Long auditid=getUserId();
        long roleId=getUser().getRoleId();
        FileAuditDO fileAuditDO=null;
        if(roleId==1){
            auditid=null;
        }
        fileAuditDO=fileAuditService.getCountAudit(auditid);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        //已审批
        int data1[] = new int[15];
        //未审批
        int data2[] = new int[15];
        //时间
        String timeArray[] = new String[15];
        for(int i =0;i<15;i++){
            String time = df.format(new Date().getTime()-(14-i)*24*60*60*1000);
            //已审批
            int num1=fileAuditService.getCountAuditByTime(time,auditid,1);
            //未审批
            int num2=fileAuditService.getCountAuditByTime(time,auditid,0);
            data1[i]=num1;
            data2[i]=num2;
            timeArray[i]=time;
        }
        List<UserFileDO> fileAudit=userFileService.getFiletypeCount(auditid);
       // List<FileAuditDO> fileAudit=fileAuditService.getFiletypeCount(auditid);
        return R.ok().put("fileAuditDO",fileAuditDO).put("data1",data1).put("data2",data2).put("timeArray",timeArray).put("fileAudit",fileAudit);
    }


    /**
     * 首页分页
     */
    @ResponseBody
    @GetMapping("/getAuditLogList")
    PageDO<FileAuditDO> getAuditLogList(@RequestParam Map<String, Object> params) {
        long userId=getUserId();
        long roleId=getUser().getRoleId();
        if(roleId!=1){
            params.put("auditid",userId);
        }
        Query query = new Query(params);
        PageDO<FileAuditDO> page = fileAuditService.getAuditLogList(query);
        if(page.getTotal()>50){
            page.setTotal(50);
        }
        return page;
    }


    /**
     * 文件审批日志首页
     * @return
     */
    @GetMapping("/report")
    @RequiresPermissions("sys:fileAudit:report")
    String report(){
        return "system/log/report";
    }


    /**
     * 用户发送文件统计报表
     * @return
     */
    @GetMapping("/sendReport")
    @RequiresPermissions("sys:fileAudit:sendReport")
    String sendReport(Model model){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        model.addAttribute("startDate", getMonthDay());
        model.addAttribute("endDate", df.format(new Date().getTime()));
        return "system/log/sendReport";
    }


    /**
     * 得到过去一个月的时间日期
     */
   public String getMonthDay(){
       SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
       Calendar c = Calendar.getInstance();
       c.setTime(new Date());
       c.add(Calendar.MONTH, -1);
       Date m = c.getTime();
       String mon = df.format(m);
       return  mon;
    }


    /**
     * 用户发送文件统计报表列表
     */
    @ResponseBody
    @GetMapping("/report2")
    public PageUtils report2(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("userid",userId);
        //查询列表数据
        Query query = new Query(params);
        Query query2 = new Query(params);
        List<ReportDo> reportList = fileAuditService.reportList(query);
        int total = fileAuditService.reportCount(query2);
        PageUtils pageUtils = new PageUtils(reportList, total);
        return pageUtils;
    }


    @ResponseBody
    @GetMapping("/report2Excel")
    public ResponseEntity<byte[]> report2Excel(String deptId,String startDate,String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("deptId",deptId);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("userid",userId);
            List<ReportDo> reportList = fileAuditService.reportList(params);
            return ExcelFormatUtil.buildResponseEntity(report2Export(reportList), "用户发送文件统计报表.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream report2Export(List<ReportDo> reportList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] {"部门名称", "总数"};

        // 字段名所在表格的宽度
        int[] ints = new int[] {5000, 5000};

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

        if (reportList != null && reportList.size() > 0) {
            for (int i = 0; i < reportList.size(); i++) {
                ReportDo reportDo = reportList.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(reportDo.getTypeName());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(reportDo.getNum()); // 审批人
                cell.setCellStyle(content);
            }
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null){
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }

    /**
     * 用户发送文件统计报表柱状图和饼状图
     */
    @ResponseBody
    @GetMapping("/reportEchart")
    public R reportEchart(String deptId,String startDate,String endDate){
        Map<String, Object> params=new HashMap<>();
        long userId=getUserId();
        params.put("userid",userId);
        params.put("deptId",deptId);
        params.put("startDate",startDate);
        params.put("endDate",endDate);
        List<ReportDo> reportList = fileAuditService.reportList(params);
        return R.ok().put("reportList",reportList);
    }



    /**
     * 用户发送文件统计报表
     * @return
     */
    @GetMapping("/typeReport")
    @RequiresPermissions("sys:fileAudit:typeReport")
    String typeReport(Model model){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        model.addAttribute("startDate", getMonthDay());
        model.addAttribute("endDate", df.format(new Date().getTime()));
        return "system/log/typeReport";
    }


    /**
     * 管理员审批统计报表
     * @return
     */
    @GetMapping("/auditReport")
    @RequiresPermissions("sys:fileAudit:auditReport")
    String auditReport(Model model){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        model.addAttribute("startDate", getMonthDay());
        model.addAttribute("endDate", df.format(new Date().getTime()));
        return "system/log/auditReport";
    }


    /**
     * 管理员审批统计列表
     */
    @ResponseBody
    @GetMapping("/report5")
    public PageUtils report5(@RequestParam Map<String, Object> params){
        long userId=getUserId();
        params.put("userid",userId);
        //查询列表数据
        Query query = new Query(params);
        Query query2 = new Query(params);
        List<ReportDo> reportList = fileAuditService.auditReportList(query);
        int total = fileAuditService.auditReportCount(query2);
        PageUtils pageUtils = new PageUtils(reportList, total);
        return pageUtils;
    }


    @ResponseBody
    @GetMapping("/report5Excel")
    public ResponseEntity<byte[]> report5Excel(String deptId,String startDate,String endDate){
        try {
            Map<String, Object> params= new HashMap<>();
            params.put("deptId",deptId);
            params.put("startDate",startDate);
            params.put("endDate",endDate);
            long userId=getUserId();
            params.put("userid",userId);
            List<ReportDo> reportList = fileAuditService.auditReportList(params);
            return ExcelFormatUtil.buildResponseEntity(report5Export(reportList), "管理员审批统计.xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private InputStream report5Export(List<ReportDo> reportList) {
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] { "管理员名称", "部门名称", "总数"};

        // 字段名所在表格的宽度
        int[] ints = new int[] { 5000, 5000, 5000};

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);

        if (reportList != null && reportList.size() > 0) {
            for (int i = 0; i < reportList.size(); i++) {
                ReportDo reportDo = reportList.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(reportDo.getUsername());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(reportDo.getTypeName());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(reportDo.getNum()); // 审批人
                cell.setCellStyle(content);
            }
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null){
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }



    /**
     * 所有文件类型统计报表柱状图和饼状图
     */
    @ResponseBody
    @GetMapping("/auditReportEchart")
    public R auditReportEchart(String deptId,String startDate,String endDate){
        Map<String, Object> params=new HashMap<>();
        long userId=getUserId();
        params.put("deptId",deptId);
        params.put("startDate",startDate);
        params.put("endDate",endDate);
        List<ReportDo> auditReportList = fileAuditService.auditReportList(params);
        return R.ok().put("reportList",auditReportList);
    }


}



